package service

import (
	"context"
	"errors"
	"gitee.com/qian/guser/dao"
	"gitee.com/qian/guser/define"
	middleware "gitee.com/qian/guser/middleware/session"
	middlewareToken "gitee.com/qian/guser/middleware/token"
	"gitee.com/qian/guser/model"
	"gitee.com/qian/guser/shared"
	JwtModel "github.com/gogf/gf-jwt/example/model"
	"github.com/gogf/gf/frame/g"
)

var GUser = gUserService{}

type gUserService struct {
}

func (s *gUserService) Login(ctx context.Context, req *define.GUserApiLoginReq) error {
	userEntity, err := s.loginByPassport(
		req.Passport,
	)
	if err != nil {
		return err
	}
	if userEntity == nil {
		return errors.New("登陆失败")
	}
	if err := middleware.Session.SetUser(ctx, userEntity); err != nil {
		return err
	}
	shared.Context.SetUser(ctx, &model.ContextUser{
		Id:      userEntity.Id,
		Account: userEntity.Account,
	})

	return nil
}

func (s *gUserService) LoginOut(ctx context.Context) error {
	err := middleware.Session.RemoveUser(ctx)
	if err != nil {
		return err
	}
	return nil
}

func (s *gUserService) LoginToken(ctx context.Context, req *define.GUserApiLoginReq) error {
	userEntity, err := s.loginByPassport(
		req.Passport,
	)
	if err != nil {
		return err
	}
	if err := middlewareToken.Session.SetUser(ctx, userEntity); err != nil {
		return err
	}
	shared.Context.SetUser(ctx, &model.ContextUser{
		Id:      userEntity.Id,
		Account: userEntity.Account,
	})

	return nil
}

func (s *gUserService) LogoutToken(ctx context.Context) error {
	if err := middlewareToken.Session.RemoveUser(ctx); err != nil {
		return err
	}
	return nil
}

func (s *gUserService) LoginJwt(ctx context.Context, req *JwtModel.ServiceLoginReq) *model.Guser {
	userEntity, err := s.loginByPassport(
		req.Username,
	)
	if err != nil {
		return nil
	}
	shared.Context.SetUser(ctx, &model.ContextUser{
		Id:      userEntity.Id,
		Account: userEntity.Account,
	})

	return userEntity
}

func (s *gUserService) loginByPassport(passport string) (*model.Guser, error) {
	userEntity, err := s.GetUserByPassport(
		passport,
	)
	if err != nil {
		return nil, err
	}
	if userEntity == nil {
		return nil, errors.New("登陆失败")
	}
	return userEntity, nil
}

// 根据账号和密码查询用户信息，一般用于账号密码登录。
// 注意password参数传入的是按照相同加密算法加密过后的密码字符串。
func (s *gUserService) GetUserByPassport(passport string) (*model.Guser, error) {
	return dao.Guser.Where(g.Map{
		dao.Guser.Columns.Account: passport,
	}).One()
}

// 根据账号和密码查询用户信息，一般用于账号密码登录。
// 注意password参数传入的是按照相同加密算法加密过后的密码字符串。
func (s *gUserService) GetUserById(id int) (*model.Guser, error) {
	return dao.Guser.Where(g.Map{
		dao.Guser.Columns.Id: id,
	}).One()
}
